import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/components/ExpandTabBar/ExpandTabBar.dart';
import 'package:orginone/components/ProcessDetailsWidget/components/ApplyWidget.dart';
import 'package:orginone/components/ProcessDetailsWidget/components/UseTracesWidget.dart';
import 'package:orginone/config/theme/unified_style.dart';
import '../../dart/base/schema.dart';
import '../../dart/core/work/task.dart';
import '../XStatefulWidget/XStatefulWidget.dart';
import 'components/ProcessInfoWidget/ProcessInfoWidget.dart';
import 'package:orginone/dart/extension/ex_datetime.dart';
import 'package:orginone/components/ProcessDetailsWidget/components/WorkTool.dart';
import 'package:orginone/components/form/form_widget/form_tool.dart';
import 'package:orginone/dart/base/model.dart';

///办事
class ProcessDetailsWidget extends XStatefulWidget<IWorkTask> {
  ProcessDetailsWidget({super.key});

  @override
  State<ProcessDetailsWidget> createState() => _ProcessDetailsPageState();
}

class _ProcessDetailsPageState
    extends XStatefulState<ProcessDetailsWidget, IWorkTask> {
  var hideProcess = true;

  IWorkTask? todo;

  WorkNodeModel? node;

  var xAttribute = {};

  List<XForm> mainForm = [];

  List<XForm> subForm = [];

  // late TabController subTabController;

  // late TabController mainTabController;

  // late TabController tabController;

  List<String> tabTitle = [
    '办事详情',
    '历史痕迹',
  ];

  _buildMainView() {
    if (todo!.targets.isNotEmpty) {
      return ApplyWidget(
        todo: todo,
      );
    } else {
      //流程视图
      // return const Text('data');
      return _buildInstanceView();
      // return EmptyWidget(
      //   title: '数据加载错误，点击刷新',
      //   reload: () async {
      //     await todo?.loadInstance(reload: true);
      //     await controller.loadDataInfo();
      //   },
      // );
    }
  }

  Widget tabBar() {
    return Container(
      color: Colors.white,
      alignment: Alignment.centerLeft,
      child: ExpandTabBar(
        // controller: tabController,
        tabs: tabTitle.map((e) {
          return Tab(
            text: e,
            height: 60.h,
          );
        }).toList(),
        indicatorSize: TabBarIndicatorSize.label,
        indicatorColor: XColors.themeColor,
        unselectedLabelColor: Colors.grey,
        unselectedLabelStyle: TextStyle(fontSize: 22.sp),
        labelColor: XColors.themeColor,
        labelStyle: TextStyle(fontSize: 24.sp),
        isScrollable: true,
      ),
    );
  }

  _buildInstanceView() {
    return DefaultTabController(
        length: tabTitle.length,
        child: Column(
          children: [
            tabBar(),
            Expanded(
              child: TabBarView(
                // controller: tabController,
                children: [
                  todo?.instance != null ? ProcessInfoWidget(todo: todo) : Container(),
                  todo?.instance != null
                      ? UseTracesWidget(
                          todo: todo,
                        )
                      : const Text('暂无流程实例'),
                ],
              ),
            )
          ],
        ));
  }

  void showAllProcess() {
    hideProcess = false;
    // setState(() {});
  }

  Future<void> loadDataInfo(IWorkTask data) async {
    if (data.targets.isEmpty) {
      //加载流程实例数据
      await data.loadInstance();
    }
    node = WorkTool.getNodeByNodeId(todo?.instanceData?.node?.id ?? "",
        node: todo?.instanceData?.node);
    if (node != null) {
      mainForm = node!.primaryForms ?? [];

      // mainForm.value = node!.forms
      //         ?.where((element) => element.typeName == "主表")
      //         .toList() ??
      //     [];
      // mainTabController = TabController(length: mainForm.length, vsync: this);
      for (var element in mainForm) {
        element.data = getFormData(element.id);
        element.fields = todo?.instanceData?.fields?[element.id] ?? [];
        for (var field in element.fields) {
          field.field = await FormTool.initFields(field);
        }
      }
      subForm = node!.detailForms ?? [];
      // subForm.value = node!.forms
      //         ?.where((element) => element.typeName == "子表")
      //         .toList() ??
      //     [];
      // subTabController = TabController(length: subForm.length, vsync: this);
      for (var element in subForm) {
        element.data = getFormData(element.id);
        element.fields = todo?.instanceData?.fields?[element.id] ?? [];
        for (var field in element.fields) {
          field.field = await FormTool.initFields(field);
        }
      }
      // setState(() {});
    }
  }

  FormEditData getFormData(String id) {
    final source = <AnyThingModel>[];
    if (todo?.instanceData?.data != null &&
        todo?.instanceData?.data![id] != null) {
      final beforeData = todo?.instanceData!.data![id]!;
      if (beforeData != null) {
        final nodeData = beforeData.where((i) => i.nodeId == node?.id).toList();
        if (nodeData.isNotEmpty) {
          return nodeData.last;
        }
      }
    }
    var data = FormEditData(
      nodeId: node?.id,
      // creator: belong.userId,
      createTime: DateTime.now().toDateString(format: 'yyyy-MM-dd hh:mm:ss.S'),
      before: [], after: [],
    );
    data.before = List.from(source);
    data.after = List.from(source);
    return data;
  }

  @override
  void initState() {
    // tabController = TabController(length: tabTitle.length, vsync: this);
    super.initState();
  }

  @override
  Widget buildWidget(BuildContext context, IWorkTask data) {
    todo = data;
    return FutureBuilder(
      builder: (context, sho) {
        if (sho.connectionState == ConnectionState.done) {
          return _buildMainView();
        }
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
      future: loadDataInfo(data),
    );
  }
}
